<script setup lang="ts">
import type { FormInstance } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import { ${EntityName}Api } from '@/apis'
import { useForm } from '@/hooks';

const emit = defineEmits<{
  (e: 'change'): void
}>()

const visible = ref(false)
const loading = ref(false)
const readonly = ref(true)

const dataId = ref('')
const dataDetail = ref<${EntityName}Api.${EntityName}DetailResp>()
const formRef = ref<FormInstance>()

const { form, resetForm } = useForm({
  <#list fieldConfigs as fieldConfig>
  <#if fieldConfig.showInForm>
  ${fieldConfig.fieldName}: null,
  </#if>
  </#list>
})

const rules: FormInstance['rules'] = {
  <#list fieldConfigs as fieldConfig>
  <#if fieldConfig.isRequired>
  ${fieldConfig.fieldName}: [{ required: true, message: '请输入${fieldConfig.comment}' }],
  </#if>
  </#list>
}

// 查询详情
const getDataDetail = async () => {
  dataDetail.value = await ${EntityName}Api.getDetail(dataId.value)
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  loading.value = false
}

// 打开详情
const open = async (id: string) => {
  dataId.value = id
  loading.value = true
  visible.value = true
  readonly.value = true
  getDataDetail()
}

// 保存
const onSave = async () => {
  try {
    const isInvalid = await formRef.value?.validate()
    if (isInvalid) {
      return false
    }
    await ${EntityName}Api.update(form, dataId.value)
    Message.success('修改成功')
    emit('change')
    visible.value = false
    return true
  } catch {
    return false
  }
}

// 取消
const onCancel = () => {
  readonly.value = true
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  formRef.value?.clearValidate()
}

// 编辑
const onEdit = () => {
  readonly.value = false
}

// 重置
const reset = () => {
  formRef.value?.resetFields()
  resetForm()
}

defineExpose({ open })
</script>

<template>
  <ProFormPanel
    v-model:visible="visible"
    title="${businessName}详情"
    :loading="loading"
    :footer="false"
  >
    <a-form ref="formRef" layout="vertical" :model="form" :rules :readonly>
      <a-card title="基础信息" class="section">
        <template #extra>
          <ReadonlyEditButton
            :readonly="readonly"
            :deleteable="false"
            @edit="onEdit"
            @cancel="onCancel"
            @save="onSave"
          />
        </template>
        <a-row :gutter="28">
          <#list fieldConfigs as fieldConfig>
          <readonly-form-item label="${fieldConfig.comment}" field="${fieldConfig.fieldName}">
            <a-input v-model.trim="form.${fieldConfig.fieldName}" placeholder="请输入${fieldConfig.comment}"/>
          </readonly-form-item>
          </#list>
        </a-row>
      </a-card>
    </a-form>
  </ProFormPanel>
</template>

<style lang="less" scoped></style>
